

package com.gx.rabbit.sender;

import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Author Liu-pj
 * @Date 2023/3/9 15:36
 * @Desc 消息发送
 **/
public class RabbitMqSender {
    private static final Logger log = LoggerFactory.getLogger(RabbitMqSender.class);
    private static final MessageProperties MESSAGE_PROPERTIES = new MessageProperties();

    static {
        MESSAGE_PROPERTIES.setContentType("application/json");
    }

    @Resource
    private RabbitTemplate rabbitTemplate;

    public RabbitMqSender() {
    }

    public void send(String exchange, String routingKey, Object msgBody) {
        String payloadStr = JSONUtil.toJsonStr(msgBody);
        log.info("send(): exchange:{} routingKey:{} payload:{}", exchange, routingKey, payloadStr);
        Message message = new Message(payloadStr.getBytes(), MESSAGE_PROPERTIES);
        String messageId = UUID.randomUUID().toString();
        message.getMessageProperties().setMessageId(messageId);

        try {
            this.rabbitTemplate.convertAndSend(exchange, routingKey, message, new CorrelationData(messageId));
            log.info("message sent, ID:{}", messageId);
        } catch (Exception var8) {
            log.error("消息发送失败,失败的原因：{}", var8.getMessage(), var8);
        }

    }
}
